import time
import requests
from lxml import etree
import os



if not os.path.exists('./images'):
    os.makedirs('./images')
session = requests.Session()
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
res = session.get("https://www.hdbz.net/", headers=headers)
content = res.content.decode()
html = etree.HTML(content)
container = html.xpath('//div[@class="pic-auto pic-list"]')[0] if html.xpath('//div[@class="pic-auto pic-list"]') else None
if container is not None:
    items = container.xpath('.//a')
    for item in items:
        href = item.get('href')
        if href:
            href = f"https://www.hdbz.net{href}"
            print(f"正在获取详情页 {href}")
            try:
                detail_res = session.get(href, headers=headers)
                detail_html = etree.HTML(detail_res.content.decode())
                detail_info = detail_html.xpath('//div[contains(@class, "pic-preview")]/img')
                if detail_info:
                    detail_image_name = detail_info[0].get('alt')
                    detail_image_url = detail_info[0].get('src')
                    detail_img_res = session.get(detail_image_url, headers=headers)
                    with open(f"./images/{detail_image_name}_detail.jpg", "wb") as f:
                        f.write(detail_img_res.content)
                    thumb_url = item.xpath('.//img/@data-original')
                    if thumb_url:
                        thumb_url = thumb_url[0]
                        thumb_img_res = session.get(thumb_url, headers=headers)
                        with open(f"./images/{detail_image_name}_thumb.jpg", "wb") as f:
                            f.write(thumb_img_res.content)
                else:
                    print(f"可能遇见了合集")
            except Exception as e:
                print(f"请求详情页 {href} 时出错: {e}")
            time.sleep(1)
    